﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Linq.Expressions;

namespace System.Web.UI.WebControls
{
    public static class ExtensoesMetodos
    {
        #region [ DropDownList ]
        public static void DataBind(this DropDownList dropDownList, object dataSource, string dataTextField, string dataValueField)
        {
            dropDownList.ClearSelection();
            dropDownList.Items.Clear();
            dropDownList.DataSource = dataSource;
            dropDownList.DataTextField = dataTextField;
            dropDownList.DataValueField = dataValueField;
            dropDownList.DataBind();
        }
        #endregion [ DropDownList ]

        public static List<T> Sort<T>(this IEnumerable<T> source, string sortExpression)
        {
            string[] sortParts = sortExpression.Split(' ');
            var param = Expression.Parameter(typeof(T), string.Empty);
            try
            {
                var property = Expression.Property(param, sortParts[0]);
                var sortLambda = Expression.Lambda<Func<T, object>>(Expression.Convert(property, typeof(object)), param);

                if (sortParts.Length > 1 && sortParts[1].Equals("descending", StringComparison.OrdinalIgnoreCase))
                {
                    return source.AsQueryable<T>().OrderByDescending<T, object>(sortLambda).ToList();
                }
                return source.AsQueryable<T>().OrderBy<T, object>(sortLambda).ToList();
            }
            catch (ArgumentException)
            {
                return source.ToList();
            }
        }

        #region [ Repeater ]
        public static void DataBind(this Repeater repeater, object dataSource)
        {
            repeater.DataSource = dataSource;
            repeater.DataBind();
        }
        #endregion [ Repeater ]
    }
}
